package net.zjitc.dao.Impl;

import net.zjitc.dao.CategorySecondDao;
import net.zjitc.pojo.Category;
import net.zjitc.pojo.CategorySecond;
import net.zjitc.utils.db.C3P0Utils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * Created by dell on 2017/11/18.
 */
public class CategorySecondDaoImpl implements CategorySecondDao {
    QueryRunner runner=new QueryRunner(C3P0Utils.getDataSource());
    public List<CategorySecond> findAllCategorySecond() {
        String sql="select * from categorysecond";
        try {
            List<CategorySecond> list= (List<CategorySecond>) runner.query(sql,new BeanListHandler(CategorySecond.class));
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void CategorySecondAdd(CategorySecond categorySecond) {
        String sql="insert into categorysecond (csname,cid) values (?,?)";
        try {
            runner.update(sql,categorySecond.csname,categorySecond.category.cid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public CategorySecond findCategorySecondById(String csid) {
        String sql="select * from categorysecond where csid =?";
        try {
            Map<String,Object> map=runner.query(sql,new MapHandler(),csid);
            Category category=new Category();
            CategorySecond categorySecond=new CategorySecond();

            BeanUtils.populate(category,map);
            BeanUtils.populate(categorySecond,map);

            categorySecond.setCategory(category);
            return categorySecond;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void CategorySecondEdit(CategorySecond categorySecond) {
        String sql="update categorysecond set csname=?,cid=? where csid=?";
        try {
            runner.update(sql,categorySecond.csname,categorySecond.category.cid,categorySecond.csid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void CategorySecondDelete(String csid) {
        String sql="delete from categorysecond where csid =?";
        try {
            runner.update(sql,csid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public List<CategorySecond> findByCid(int cid) {
        String sql="select * from categorysecond where cid=?";
        try {
            List<CategorySecond> cslist= (List<CategorySecond>) runner.query(sql,new BeanListHandler(CategorySecond.class),cid);
            return cslist;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
